package com.car.util;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Stack;

import com.mysql.jdbc.PreparedStatement;

public class ConnectionPool {

	Stack<Connection> st = new Stack<Connection>();
	private static ConnectionPool instance = new ConnectionPool();
	public static int initialPoolSize = 10;
	public static String dbName = "carvoice";
	public static String userName = "root";
	public static String userPasswd = "zhouzhou100428";
	public static String host = "localhost";

	public synchronized static Connection getConnection(String db, String user, String pwd) {
		dbName = db;
		userName = user;
		userPasswd = pwd;
		if (instance.st.size() > 0)
			return instance.st.pop();
		else
			return createConnection();
	}

	public synchronized static Connection getConnection(String db, String user, String pwd, String hostip) {
		dbName = db;
		userName = user;
		userPasswd = pwd;
		host = hostip;
		if (instance.st.size() > 0)
			return instance.st.pop();
		else
			return createConnection();
	}

	public synchronized static Connection getConnection() {
		if (instance.st.size() > 0)
			return instance.st.pop();
		else
			return createConnection();
	}

	synchronized static void returnConnection(Connection conn) {
		instance.st.push(conn);
	}

	private static Connection createConnection() {
		String url = "jdbc:mysql://" + host + ":3306/" + dbName + "?user=" + userName + "&password=" + userPasswd
				+ "&useCursorFetch=true&defaultFetchSize=50000";
		Connection connection;
		Connection proxy = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(url);
			ConnectionProxy handler = new ConnectionProxy(connection);
			proxy = (Connection) Proxy.newProxyInstance(connection.getClass().getClassLoader(),
					new Class[] { Connection.class }, handler);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return proxy;
	}

	public static void close(ResultSet rs, Statement st, Connection conn) {
		try {

			rs.close();
			st.close();
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Statement st, Connection conn) {
		try {

			st.close();
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(PreparedStatement ps, Connection conn) {
		try {

			ps.close();
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
